#include "building_type.hpp"
#include "wml_node.hpp"
#include "wml_utils.hpp"

namespace {
std::map<std::string, building_type_ptr> cache;
}

void building_type::init(wml::const_node_ptr node)
{
	wml::node::const_child_iterator i1 = node->begin_child("building");
	wml::node::const_child_iterator i2 = node->end_child("building");
	for(; i1 != i2; ++i1) {
		building_type_ptr b(new building_type(i1->second));
		cache[b->id()] = b;
	}
}

const_building_type_ptr building_type::get(const std::string& key)
{
	std::map<std::string, building_type_ptr>::const_iterator i = cache.find(key);
	if(i != cache.end()) {
		return i->second;
	} else {
		return const_building_type_ptr();
	}
}

std::vector<const_building_type_ptr> building_type::get_all()
{
	std::vector<const_building_type_ptr> all;
	for(std::map<std::string, building_type_ptr>::const_iterator i = cache.begin(); i != cache.end(); ++i) {
		all.push_back(i->second);
	}

	return all;
}

building_type::building_type(wml::const_node_ptr node)
  : id_(node->attr("id")), cost_(wml::get_int(node, "cost"))
{
	wml::const_node_ptr storage = node->get_child("storage");
	if(storage) {
		for(wml::node::const_attr_iterator i = storage->begin_attr(); i != storage->end_attr(); ++i) {
			storage_[i->first] = wml::get_int(storage, i->first);
		}
	}
}

int building_type::storage(const std::string& item) const
{
	std::map<std::string, int>::const_iterator i = storage_.find(item);
	if(i != storage_.end()) {
		return i->second;
	} else {
		return 0;
	}
}
